/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.service.content.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cms.constant.ConstantEnum.ContentTypes;
import org.grayrabbit.cms.constant.ConstantEnum.OperAct;
import org.grayrabbit.cms.constant.ContentStatic;
import org.grayrabbit.cms.constant.DictionaryStaticValues;
import org.grayrabbit.cms.dao.category.CategoryDao;
import org.grayrabbit.cms.dao.content.ContentAttachDao;
import org.grayrabbit.cms.dao.content.ContentDao;
import org.grayrabbit.cms.dao.content.FlashContentDao;
import org.grayrabbit.cms.dao.content.LinkContentDao;
import org.grayrabbit.cms.dao.content.PictureContentDao;
import org.grayrabbit.cms.dao.content.SoftwareContentDao;
import org.grayrabbit.cms.dao.content.VideoContentDao;
import org.grayrabbit.cms.dao.system.OperLogDao;
import org.grayrabbit.cms.dao.topic.TopicContentDao;
import org.grayrabbit.cms.dao.topic.TopicDao;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.Category;
import org.grayrabbit.cms.entity.Content;
import org.grayrabbit.cms.entity.ContentAttach;
import org.grayrabbit.cms.entity.FlashContent;
import org.grayrabbit.cms.entity.LinkContent;
import org.grayrabbit.cms.entity.OperLog;
import org.grayrabbit.cms.entity.PictureContent;
import org.grayrabbit.cms.entity.SoftwareContent;
import org.grayrabbit.cms.entity.Topic;
import org.grayrabbit.cms.entity.TopicContent;
import org.grayrabbit.cms.entity.VideoContent;
import org.grayrabbit.cms.service.content.ContentService;
import org.grayrabbit.cms.util.DateUtil;
import org.grayrabbit.cms.vo.content.ContentAttachBean;
import org.grayrabbit.cms.vo.content.ContentBean;
import org.grayrabbit.dao.util.Page;
import org.grayrabbit.dao.util.QueryCondition;
import org.grayrabbit.service.impl.GenericServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <b>OperLog</b>的service实现类，事务加此处：
 * 
 * @version 1.0,创建时间: 2011-05-16 14:40:11
 */
@Service
@Transactional
public class ContentServiceImpl extends GenericServiceImpl implements
		ContentService {
	private  static final Logger  logger = LoggerFactory.getLogger(ContentServiceImpl.class);
	/**
	 * 注入dao层：
	 */
	@Autowired
	@Qualifier("contentDaoImpl")
	private ContentDao contentDao;
	
	@Autowired
	@Qualifier("softwareContentDaoImpl")
	private SoftwareContentDao softwareContentDao;
	
	@Autowired
	@Qualifier("pictureContentDaoImpl")
	private PictureContentDao pictureContentDao;
	
	@Autowired
	@Qualifier("videoContentDaoImpl")
	private VideoContentDao videoContentDao;
	
	@Autowired
	@Qualifier("linkContentDaoImpl")
	private LinkContentDao linkContentDao;
	
	@Autowired
	@Qualifier("flashContentDaoImpl")
	private FlashContentDao flashContentDao;
	

	@Autowired
	@Qualifier("contentAttachDaoImpl")
	private ContentAttachDao contentAttachDao;

	@Autowired
	@Qualifier("categoryDaoImpl")
	private CategoryDao categoryDao;

	@Autowired
	@Qualifier("topicDaoImpl")
	private TopicDao topicDao;

	@Autowired
	@Qualifier("topicContentDaoImpl")
	private TopicContentDao topicContentDao;
	
	@Autowired
	@Qualifier("operLogDaoImpl")
	private OperLogDao operLogDao;

	/**
	 * 此方法执行时为只读事务：
	 * 
	 * @see ContentService#getOperLog(String)
	 */
	@Transactional(readOnly = true)
	public Content getContent(final String contentId) {
		try{
			Content content = contentDao.findById(contentId);
			contentDao.initialize(content);
			contentDao.initialize(content.getCategory());
			contentDao.initialize(content.getContentAttachs());
			contentDao.initialize(content.getTopic());
			if (content.getCategory() != null) {
				contentDao.initialize(content.getCategory().getSite());
			}
			return content;
		}catch(Exception e){
		}
		return new Content();
	}
	
	/**生成时 调用 返回实际的内容  非代理类内容  以获取 各个类型内容的私有 属性*/
	@Transactional(readOnly = true)
	public Content getRealContent(final String contentId) {
		Content content = contentDao.findById(contentId);
		if(ContentTypes.CONTENT.equals(content.getContextType())){
			loadContentFileds(content);
			return content;
		}else if(ContentTypes.LINK.equals(content.getContextType())){
			LinkContent c = linkContentDao.findById(contentId);
			loadContentFileds(c);
			return c;
		}else if(ContentTypes.PICTURE.equals(content.getContextType())){
			PictureContent c = pictureContentDao.findById(contentId);
			loadContentFileds(c);
			return c;
		}else if(ContentTypes.SOFT.equals(content.getContextType())){
			SoftwareContent c = softwareContentDao.findById(contentId);
			loadContentFileds(c);
			return c;
		}else if(ContentTypes.FLASH.equals(content.getContextType())){
			FlashContent c = flashContentDao.findById(contentId);
			loadContentFileds(c);
			return c;
		}else if(ContentTypes.VIDEO.equals(content.getContextType())){
			VideoContent c = videoContentDao.findById(contentId);
			loadContentFileds(c);
			return c;
		}else{
			return content;
		}	
	}
	
	private void loadContentFileds(Content content){
		contentDao.initialize(content);
		contentDao.initialize(content.getCategory());
		contentDao.initialize(content.getContentAttachs());
		contentDao.initialize(content.getTopic());
		if (content.getCategory() != null) {
			contentDao.initialize(content.getCategory().getSite());
		}
	}
	

	/**
	 * @see ContentService#delete(String)
	 */
	@Transactional
	public void delete(final Content content) {
		contentDao.makeTransient(content);
	}

	/**
	 * @see ContentService#save(OperLog)
	 */
	@Transactional
	public void save(final Content content, final Admin user, final String cflag) {
		Date n = new Date();
		if (content != null) {
			if (StringUtils.isBlank(content.getContentId())) {
				if (StringUtils.isNotBlank(user.getLoginName())) {
					content.setCreateLoginName(user.getLoginName());
					content.setUpdateLoginName(user.getLoginName());
				}
				if (StringUtils.isNotBlank(user.getRealName())) {
					content.setCreateRealName(user.getRealName());
					content.setUpdateRealName(user.getRealName());
				} else {
					content.setCreateRealName(user.getLoginName());
					content.setUpdateRealName(user.getLoginName());
				}
				content.setCreateTime(n);
				content.setUpdateTime(n);
				content.setContentStatus(DictionaryStaticValues.CONTENT_STATUS_NEW);
				content.setIsLocked(Boolean.FALSE);
			} else if(DictionaryStaticValues.CONTENT_STATUS_UNLOCK.equals(cflag)){//解锁操作
			    /* 解锁不记录修改人信息 */ 
				content.setIsLocked(Boolean.FALSE); 
			}else {
				if (DictionaryStaticValues.CONTENT_STATUS_SUCCESS.equals(cflag) 
						|| DictionaryStaticValues.CONTENT_STATUS_FAIL.equals(cflag)) {//审核通过或者不通过，沈永生后期补充说明 2012.2.14
					content.setAuditLoginName(user.getLoginName());
					content.setAuditRealName(user.getRealName());
					content.setAuditTime(n);
					content.setUpdateLoginName(user.getLoginName());
					content.setUpdateRealName(user.getRealName());
					content.setUpdateTime(n);
					content.setContentStatus(cflag);
					content.setIsLocked(Boolean.FALSE);	
				} else if (DictionaryStaticValues.CONTENT_STATUS_PUBLISH.equals(cflag)) {
					content.setPublishLoginName(user.getLoginName());
					content.setPublishRealName(user.getRealName());
					if (content.getPublishTime() == null) {
						content.setPublishTime(n);
					}
					content.setContentStatus(cflag);
					content.setIsLocked(Boolean.FALSE);	
				} else if ( DictionaryStaticValues.CONTENT_STATUS_LOCK.equals(cflag)) {
					/*锁定不记录修改信息*/
					content.setIsLocked(Boolean.TRUE);
				} else if(cflag!=null){//保存的时候
					if(cflag.equals(DictionaryStaticValues.CONTENT_STATUS_NEW)
							||cflag.equals(DictionaryStaticValues.CONTENT_STATUS_PUBLISH)){
							content.setUpdateRealName(user.getRealName());
					}else{
						content.setUpdateRealName(user.getRealName());
						content.setTemporaryUser(user.getRealName());
					}
					content.setUpdateLoginName(user.getLoginName());
					content.setUpdateTime(n);
					content.setContentStatus(DictionaryStaticValues.CONTENT_STATUS_NEW);
					content.setIsLocked(Boolean.FALSE);					
				}
			}
		}
		contentDao.merge(content);
	}

	@Transactional
	public void save2(final Content content) {
		contentDao.makePersistent(content);		
	}
	
	@Transactional
	public void savePublish(List<String> list, Admin admin, String contentStatusPublish,String contentPublishType,String ip){
		for(String id:list){
			if(id.indexOf("_tq")<0){
				Content content = contentDao.findById(id);
				save(content,admin,contentStatusPublish);
				OperLog operLog = new OperLog();
				if(StringUtils.isBlank(ip)||ip.equals("localhost")){
					loadOperLogInfo(operLog,admin.getLoginName(), admin.getRealName(), contentPublishType, OperAct.PUBLISH.getValue(), id,"localhost");
					operLog.setMemo(admin.getRealName()+" , "+DateUtil.formatDateToString(new Date(), "yyyy-MM-dd HH:mm:ss") 
							+"在(模块) "+contentPublishType+" 中，对ID为： "+id+" 的对象进行了 "+OperAct.AUTOPUBLISH.getValue()+" 操作");
					operLogDao.makePersistent(operLog);					
				}
				else{
					
					loadOperLogInfo(operLog,admin.getLoginName(), admin.getRealName(), contentPublishType, OperAct.PUBLISH.getValue(), id,ip);
					
					operLog.setMemo(admin.getRealName()+" , "+DateUtil.formatDateToString(new Date(), "yyyy-MM-dd HH:mm:ss") 
							+"在(模块) "+contentPublishType+" 中，对ID为： "+id+" 的对象进行了 "+OperAct.PUBLISH.getValue()+" 操作");
					operLogDao.makePersistent(operLog);	
				}
			}
		}
	}
	
	/**
	 * @param loginName
	 * @param realName
	 * @param modelType
	 * @param act
	 * @param ObjectId  
	 *  装载日志信息(memo除外)
	 */
	private void loadOperLogInfo(OperLog operLog,String loginName, 
			String realName ,String modelType,String act,String ObjectId,String ip){
		operLog.setLoginName(loginName);
		operLog.setRealName(realName);
		operLog.setOperFunc(modelType);
		operLog.setOperAct(act);
		operLog.setOperObjectId(ObjectId);
		operLog.setOperIp(ip);
		operLog.setOperTime(new Date());
	} 

	/**
	 * 此方法执行时为只读事务：
	 * 
	 * @see ContentService#getPage(ContentBean)
	 */
	@Transactional(readOnly = true)
	public Page<Content> getPage(final ContentBean contentBean) {
		Page<Content> page = new Page<Content>();
		page.setTotal(contentDao.count(contentBean));
		page.setResult(contentDao.findByQc(contentDao.assembly(contentBean)));
		return page;
	}

	/**
	 * 此方法执行时为只读事务：
	 * 
	 * @see ContentService#list(Page, ContentBean)
	 */
	public void list(Page<Content> page, ContentBean contentBean) {
		if (page == null)
			return;
		if (page.isAutoCount()) {
			page.setTotal(contentDao.count(contentBean));
		}
		page.setResult(contentDao.findByPage(page, contentBean));
	}

	/**
	 * 根据文章状态获取文章总数
	 * 
	 * @param contentBean
	 * @return
	 */
	public int getCount(ContentBean cb) {
		return contentDao.count(cb);
	}

	/**
	 * 根据主键id列删除，批量删除OperLog
	 * 
	 * @see ContentService#delete(String[])
	 */
	public void delete(final String[] key) {
		int i = 0;
		for (String id : key) {
			ContentAttachBean obj = new ContentAttachBean();
			obj.setContent(contentDao.findById(id));
			List<ContentAttach> list = contentAttachDao.findContentAttch(obj);
			for (int j = 0; j < list.size(); j++) {
				contentAttachDao.makeTransient(list.get(j));
				if (j == MAX_CLEAR)
					contentAttachDao.clear();
			}
			contentDao.makeTransient(contentDao.findById(id));
			i++;
			if (i == MAX_CLEAR)
				contentDao.clear();
			if (ContentStatic.cab != null) {
				ContentStatic.cab.remove(id);
			}
		}

	}

	/**
	 * 填充分页组件的NotIn查询：(名称参数)
	 * 
	 * @param page
	 * @param contentBean
	 */
	public void listNotIn(Page<Content> page, ContentBean contentBean) {
		if (page == null)
			return;
		if (page.isAutoCount()) {
			page.setTotal(contentDao.countNotIn(contentBean));
		}
		page.setResult(contentDao.findByPageNotIn(page, contentBean));
	}

	/**
	 * 根据栏目id查询文章
	 * 
	 * @return
	 */
	public List<Content> findByCatId(String catId) {
		return contentDao.findByCatId(catId);
	}

	@Transactional(readOnly = true)
	public List<Content> findAll() {
		return contentDao.findAll();
	}

	public List<Content> findAll(ContentBean contentBean) {
		return contentDao.findAll(contentBean);
	}

	@Transactional(readOnly = true)
	public List<Content> ftlFindAll(String catName,String catShortName,String siteId,String[] docIds, String flag,
			String[] catIds, String[] contentTypes, String begintime,
			String endTime, String[] keywords, String condition,
			String orderBy, long[] limit, boolean pagination, long pageSize,
			long crrunetPage) {
		try {
			Set<String> set = new HashSet<String>();
			if(StringUtils.isNotBlank(catName)){
				String id = categoryDao.findCatIdByCatName(catName,catShortName,siteId,null);
				if(StringUtils.isBlank(id)){
					return new ArrayList<Content>();
				}else{
					set.add(id);
				} 					
			}else{ 
				for (String i : catIds) {
					findAllCateIds(set, i);
				}
			}
			String[] str = new String[set.size()];
			int i = 0;
			for (String o : set) {
				str[i] = o;
				i++;
			}
			set.clear();
			return contentDao.ftlFindAll(docIds, flag, str, contentTypes,
					begintime, endTime, keywords, condition, orderBy, limit,
					pagination, pageSize, crrunetPage);
		} catch (Exception e) {
			logger.error("内容查询异常", e);
		}
		return new ArrayList<Content>();
	}
	
	public List<Content> darkblueFindAll(String[] siteId, String[] docIds, String flag, String[] catIds, String[] topicIds,
			String[] contentTypes, String begintime, String endTime,
			String[] keywords, String condition, String orderBy, long[] limit,
			boolean pagination, long pageSize, long crrunetPage,
			boolean showLike, boolean rondom, long maxPageCount, String articleType, String rollannounceSimpleName) {
		try {
			if(StringUtils.isNotBlank(rollannounceSimpleName)) {
				List<Category> cats = categoryDao.findRollannounceCat(siteId, rollannounceSimpleName);
				if(cats.size() > 0) {
					StringBuffer buf = new StringBuffer();
					for(Category cat : cats) {
						buf.append(cat.getCategoryId()).append(",");
					}
					String rollannounceCatIds = buf.toString();
					catIds = rollannounceCatIds.split(",");
					cats.clear();
				}
			}
			Set<String> set = new HashSet<String>();
			for (String i : catIds) {
				findAllCateIds(set, i);
			}
			String[] str = new String[set.size()];
			int i = 0;
			for (String o : set) {
				str[i] = o;
				i++;
			}
			set.clear();
			return contentDao.darkblueFindAll(siteId, docIds, flag, str,topicIds, contentTypes,
					begintime, endTime, keywords, condition, orderBy, limit,
					pagination, pageSize, crrunetPage, showLike, rondom, maxPageCount, articleType);
		} catch (Exception e) {
			logger.error("内容查询异常", e);
		}
		return new ArrayList<Content>();
	}

	public Set<String> findAllCateIds(Set<String> set, String catId) {
		set.add(catId);
		List<Category> list = categoryDao.findByParentId(catId, null);
		for (Category c : list) {
			set.add(c.getCategoryId());
			categoryDao.initialize(c);
			categoryDao.initialize(c.getCategories());
			if (c.getCategories() == null || c.getCategories().isEmpty())
				continue;
			for (Category cat : c.getCategories()) {
				findAllCateIds(set, cat.getCategoryId());
			}
		}
		list.clear();
		categoryDao.clear();
		return set;
	}

	public List<Content> ftlFindAllTopic(String[] docIds, String flag,
			String topicId, String[] contentTypes, String begintime,
			String endTime, String condition, String orderBy, long[] limit,
			boolean pagination, long pageSize, long crrunetPage,
			boolean showLike, boolean rondom, long maxPageCount) {
		try {
			String[] keyword = null;
			String[] excludeIds = null;
			if (StringUtils.isNotBlank(topicId)) {
				Topic t = topicDao.findById(topicId);
				if (t != null && StringUtils.isNotBlank(t.getKeywords())) {
					keyword = t.getKeywords().split(",");// 关键词 匹配文章
				}
				if (t != null) {
					List<TopicContent> list = topicContentDao
							.findByTopicId(topicId);
					if (list != null && !list.isEmpty()) {
						excludeIds = new String[list.size()];// 屏蔽文章列表
						for (int i = 0; i < list.size(); i++) {
							if (list.get(i).getContent() == null
									|| list.get(i).getContent().getContentId() == null)
								continue;
							excludeIds[i] = list.get(i).getContent()
									.getContentId();
						}
						list.clear();
					}
					t = null;
				}
			}
			return contentDao.ftlFindAllTopic(docIds, flag, topicId, keyword,
					excludeIds, contentTypes, begintime, endTime, condition,
					orderBy, limit, pagination, pageSize, crrunetPage,
					showLike, rondom, maxPageCount);
		} catch (Exception e) {
			logger.error("内容查询异常", e);
		}
		return new ArrayList<Content>();
	}

	public int findTotalNum(QueryCondition qc) {
		return contentDao.findTotalNum(qc);
	}


	/**
	 * 根据站点ID获取文章
	 * 
	 * @param list
	 * @param currentContentIndex
	 * @param max
	 * @return
	 */
	public List<String> findContentIdsBySiteId(List<String> siteIds,int currentContentIndex, int max) {
		Iterator<Content> iterator = contentDao.findContentBySiteIds(siteIds,currentContentIndex);
		List<String> contentIds = new ArrayList<String>();
		while(iterator.hasNext()){
			Content content = iterator.next();
			currentContentIndex++;
			if(needPublish(content,true)){
				contentIds.add(content.getContentId());
			}
			if(contentIds.size()==max){
				break;
			}
		}
		contentIds.add(0, currentContentIndex+"");
		return contentIds;
		
	}
	
	private boolean needPublish(Content content,boolean full) {
		if("LinkContent".equals(content.getContextType()))
			return false;
		if(content.getCategory()!=null){
			if(content.getCategory().getIsAudit()!=null && content.getCategory().getIsAudit().booleanValue()){
				if(full)
					return DictionaryStaticValues.CONTENT_STATUS_SUCCESS.equalsIgnoreCase(content.getContentStatus())
						|| DictionaryStaticValues.CONTENT_STATUS_PUBLISH.equalsIgnoreCase(content.getContentStatus());
				else
					return DictionaryStaticValues.CONTENT_STATUS_SUCCESS.equalsIgnoreCase(content.getContentStatus());
			}else{
				if(full)
					return DictionaryStaticValues.CONTENT_STATUS_NEW.equalsIgnoreCase(content.getContentStatus())
						|| DictionaryStaticValues.CONTENT_STATUS_PUBLISH.equalsIgnoreCase(content.getContentStatus());
				else
					return DictionaryStaticValues.CONTENT_STATUS_NEW.equalsIgnoreCase(content.getContentStatus());
			}
		}else if(content.getTopic()!=null){
			if(content.getTopic().getIsAudit()!=null && content.getTopic().getIsAudit().booleanValue()){
				if(full)
					return DictionaryStaticValues.CONTENT_STATUS_SUCCESS.equalsIgnoreCase(content.getContentStatus())
						|| DictionaryStaticValues.CONTENT_STATUS_PUBLISH.equalsIgnoreCase(content.getContentStatus());
				else
					return DictionaryStaticValues.CONTENT_STATUS_SUCCESS.equalsIgnoreCase(content.getContentStatus());
			}else{
				if(full)
					return DictionaryStaticValues.CONTENT_STATUS_NEW.equalsIgnoreCase(content.getContentStatus())
						|| DictionaryStaticValues.CONTENT_STATUS_PUBLISH.equalsIgnoreCase(content.getContentStatus());
				else
					return DictionaryStaticValues.CONTENT_STATUS_NEW.equalsIgnoreCase(content.getContentStatus());
			}
		}
		
		return false;
	}
	
	/**
	 * 根据站点ID获取增量文章
	 * @param list
	 * @param currentContentIndex
	 * @param max
	 * @return
	 */
	public List<String> findMoreContentIdsBySiteId(List<String> siteIds,int currentContentIndex, int max){
		Iterator<Content> iterator = contentDao.findMoreContentIdsBySiteIds(siteIds,currentContentIndex);
		List<String> contentIds = new ArrayList<String>();
		while(iterator.hasNext()){
			Content content = iterator.next();
			currentContentIndex++;
			if(needPublish(content,false)){
				contentIds.add(content.getContentId());
			}
			if(contentIds.size()==max){
				break;
			}
		}
		contentIds.add(0, currentContentIndex+"");
		return contentIds;
	}
	
	/**
	 * 根据栏目ID获取增量文章
	 * @param list
	 * @param currentContentIndex
	 * @param max
	 * @return
	 */
	public List<String> findMoreContentIdsByCatId(List<String> list,
			int currentContentIndex, int max){
		List<String> rs = new ArrayList<String>();
		for (String catId : list) {
			ContentBean contentBean = new ContentBean();
			Category category = new Category();
			category.setCategoryId(catId);
			contentBean.setCategory(category);
			contentBean.setMaxPublishTime(new Date());
			Category cat = categoryDao.findById(catId);
			if(!cat.getIsAudit()){
				contentBean.setContentStatus(DictionaryStaticValues.CONTENT_STATUS_NEW);
			}else{
				contentBean.setContentStatus(DictionaryStaticValues.CONTENT_STATUS_SUCCESS);
			}
			List<Content> contentList = contentDao.findPublish(contentBean,
					currentContentIndex, max);
			for (Content content : contentList) {
				rs.add(content.getContentId());
			}
			contentList.clear();
		}
		contentDao.clear();
		return rs;
	}

	/**
	 * 根据专题ID获取增量文章
	 * @param list
	 * @param currentContentIndex
	 * @param max
	 * @return
	 */
	public List<String> findMoreContentIdsByTopicId(List<String> list,
			int currentContentIndex, int max){
		List<String> rs = new ArrayList<String>();
		for (String topicId : list) {
			ContentBean contentBean = new ContentBean();
			Topic topic = new Topic();
			topic.setTopicId(topicId);
			contentBean.setTopic(topic);
			contentBean.setContentStatus(DictionaryStaticValues.CONTENT_STATUS_SUCCESS);
			contentBean.setMaxPublishTime(new Date());
			List<Content> contentList = contentDao.findPublish(contentBean,
					currentContentIndex, max);
			for (Content content : contentList) {
				rs.add(content.getContentId());
			}
			contentList.clear();
		}
		return rs;
	}

	/**
	 * 根据栏目ID获取文章
	 * 
	 * @param list
	 * @param currentContentIndex
	 * @param max
	 * @return
	 */
	public List<String> findContentIdsByCatId(List<String> list,int currentContentIndex, int max) {
		List<String> rs = new ArrayList<String>();
		for (String catId : list) {
			ContentBean contentBean = new ContentBean();
			Category category = new Category();
			category.setCategoryId(catId);
			contentBean.setCategory(category);
//				Category cat = categoryDao.findById(catId);
			List<Content> contentList = contentDao.findPublish(contentBean,
					currentContentIndex, max);
			for (Content content : contentList) {
				rs.add(content.getContentId());
			}
			contentList.clear();
		}
		contentDao.clear();
		return rs;
	}
	
	/**
	 * 获取待发布的文章
	 * 
	 * @param contentBean
	 * @return
	 */
	public List<Content> findAllByPublish(ContentBean contentBean) {
		List<Content> list = new ArrayList<Content>();
		if (contentBean.getCategory() != null && StringUtils.isNotBlank(contentBean.getCategory().getCategoryId())) {
			List<Category> cats = listLeafCategory(contentBean.getCategory().getCategoryId());
			for(int i=0;i<cats.size();i++){
				contentBean.setCategory(cats.get(i));
				List<Content> contents = contentDao.findPublish(contentBean);
				for(Content c:contents){
					contentDao.initialize(c.getContentAttachs());
				}
				list.addAll(contents);
			}
		}
		return list;
	}
	
	public List<Content> findAllByPublish(ContentBean contentBean,int pageSize){
		List<Content> list = new ArrayList<Content>();
		if (contentBean.getCategory() != null && StringUtils.isNotBlank(contentBean.getCategory().getCategoryId())) {
			List<Category> cats = listLeafCategory(contentBean.getCategory().getCategoryId());
			for(int i=0;i<cats.size();i++){
				contentBean.setCategory(cats.get(i));
				List<Content> contents = contentDao.findPublish(contentBean,pageSize);
				for(Content c:contents){
					contentDao.initialize(c.getContentAttachs());
				}
				list.addAll(contents);
			}
			cats.clear();
		}
		return list;
	}
	
	/**
	 * 查找所有的叶子栏目
	 * @param catId
	 * @return
	 */
	private List<Category> listLeafCategory(String catId){
		Category cat = categoryDao.findById(catId);
		categoryDao.initialize(cat);
		List<Category> list = new ArrayList<Category>();
		if(cat.getCategories()!=null&&!cat.getCategories().isEmpty()){
			for(Category c:cat.getCategories())
				list.addAll(listLeafCategory(c.getCategoryId()));
		}
		else{
			list.add(cat);
		}
		return list;
			
	}

	/**
	 * 根据专题ID获取文章
	 * 
	 * @param list
	 * @param currentContentIndex
	 * @param max
	 * @return
	 */
	public List<String> findContentIdsByTopicId(List<String> list,
			int currentContentIndex, int max) {
		List<String> rs = new ArrayList<String>();
		for (String topicId : list) {
			ContentBean contentBean = new ContentBean();
			Topic topic = new Topic();
			topic.setTopicId(topicId);
			contentBean.setTopic(topic);
			List<Content> contentList = contentDao.findPublish(contentBean,
					currentContentIndex, max);
			for (Content content : contentList) {
				rs.add(content.getContentId());
			}
			contentList.clear();
		}
		return rs;
	}

	/**
	 * 检查文章标题是否已经存在
	 * 
	 * @param role
	 * @return
	 */
	public Boolean checkNameUnique(String contentTitle) {
		return contentDao.checkNameUnique(contentTitle);
	}

	public void updateContent(Content obj) {
		contentDao.makePersistent(obj);
	}

	public void searchList(Page<Content> page, ContentBean contentBean) {
		if (page == null)
			return;
		if (page.isAutoCount()) {
			page.setTotal(contentDao.searchCount(contentBean));
		}
		page.setResult(contentDao.searchPage(page, contentBean));

	}

	public void searchPlanList(Page<Content> page, ContentBean contentBean) {
		if (page == null)
			return;
		if (page.isAutoCount()) {
			page.setTotal(contentDao.searchPlanCount(contentBean));
		}
		page.setResult(contentDao.searchPlanPage(page, contentBean));

	}

	/**
	 * 根据栏目id查询文章-多个栏目id
	 * 
	 * @param catList
	 * @return
	 */
	public List<Content> findByCats(List<String> catList) {
		return contentDao.findByCats(catList);
	}

	public List<Content> ftlFindbyIds(String[] ids) {
		List<Content> list = contentDao.findByIds(ids);
		if (list == null || list.isEmpty())
			return new ArrayList<Content>();
		List<Content> listC = new ArrayList<Content>();
		for (Content c : list) {
			contentDao.initialize(c.getContentAttachs());
//			if (!c.getContentAttachs().isEmpty())
				listC.add(c);
		}
		list.clear();
		return listC;
	}

	
	/**
	 * 根据文章id获得栏目名称
	 * @param contentId
	 * @return
	 */
    public String getCatName(String contentId){
    	return contentDao.getCatName(contentId);
    }
    
    public List<Content> ftlFindTopPosts(int num){
    	return contentDao.ftlFindTopPosts(num);
    }
	private void initUpCat(Category c,Set<String> set){		 
		set.add(c.getCategoryId());
    	categoryDao.initialize(c.getCategories());
    	for(Category cat:c.getCategories()){    		
    		initUpCat(cat, set);
    	}		 
	}
    
    public Content findPictureContent(String catId){
    	Category c= categoryDao.findById(catId);
    	Set<String> set = new HashSet<String>();     
    	initUpCat(c, set);
    	if(set.isEmpty())  return null;
    	Content content = contentDao.findDocBycatIds(set,"PictureContent");
    	if(content != null){
    		contentDao.initialize(content.getContentAttachs());
    	}
    	return content;
    }
    
    public List<Content> findContentS(String catId,int num){
    	Category c= categoryDao.findById(catId);
    	Set<String> set = new HashSet<String>();     
    	initUpCat(c, set);
    	if(set.isEmpty())  return new ArrayList<Content>();     	   
    	return contentDao.finddocsByCatIds(set, num);
    }

	public void listSite(Page<Content> page, ContentBean contentBean) {
		if (page == null)
			return;
		if (page.isAutoCount()) {
			page.setTotal(contentDao.count(contentBean));
		}		
		List<Content> list =  contentDao.findByPage(page, contentBean);
		page.setResult(list);
		for(Content c: list){
			contentDao.initialize(c.getCategory());
		}
		contentDao.clear();
	}

	@Transactional
	public int savebath(Set<Content> set) {
		int i = 0;
		for(Content c:set){
			int count= contentDao.findByTitleAndCreatedTime(c.getContentTitle(),
					c.getCreateTime(),c.getCategory().getCategoryId());
			if(count > 0 ){
			}else{
				contentDao.makePersistent(c);
				i++;				
			}				
		}
		return i;
	}
}